;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Stock.StockAllocation", [])
        .controller("StockAllocationCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "UserContextService", "Upload", "$timeout", "EventBus", "$filter", "$stateParams", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, UserContextService, Upload, $timeout, EventBus, $filter, $stateParams) {
            $scope.activeFlag = [true, false, false, false, false, false];
            $scope.datePickerFlag = [false, false];
            $scope.markInfo = {
                allCheckedBill: false,
                allCheckedMaterial: false,
                curRow: -1
            };
            $scope.submitted = false;
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.pageInfoFor = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.condition = {};
            $scope.conditionFor = {
            };
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false,
                showMateriel: false,
                showFroWardSearch: false,
                showForColConfig: false,
            };
            $scope.allotTypeList = [];
            $scope.dataList = [];
            $scope.dataListFor = [];
            // 已删除的
            $scope.dataDelList = [];
            $scope.pageInfoDel = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            var materielFieldList = [{
                    name: "零件编号",
                    width: 150,
                    dataField: "materialsNo",
                    needInput: false
                },
                {
                    name: "零件中文名",
                    width: 150,
                    dataField: "materialsDes",
                    needInput: false
                },
                {
                    name: "单位",
                    width: 100,
                    dataField: "unit",
                    needInput: false
                },
                {
                    name: "默认储位",
                    width: 180,
                    dataField: "stockLocation",
                    needInput: false
                },
                {
                    name: "实际库存",
                    width: 100,
                    dataField: "enableNum",
                    clickFn: "alterReport",
                    needInput: false
                },
                {
                    name: "调入仓库库存",
                    width: 120,
                    dataField: "enableNumOther",
                    // clickFn: "alterReport",
                    needInput: false
                },

                {
                    name: "意向占用",
                    width: 100,
                    dataField: "intentionNum",
                    needInput: false
                },
                {
                    name: "发货占用",
                    width: 100,
                    dataField: "deliveryNum",
                    needInput: false
                },
                {
                    name: "申请数量",
                    width: 100,
                    dataField: "amount",
                    needInput: true,
                    needRequired: true
                },
                {
                    name: "调出完成数",
                    width: 100,
                    dataField: "outAmount",
                    needInput: false
                },
                {
                    name: "调入完成数",
                    width: 100,
                    dataField: "inAmount",
                    needInput: false
                },
                {
                    name: "备注",
                    width: 300,
                    dataField: "remark",
                    needInput: true,
                    needRequired: false
                },
                {
                    name: "总数量",
                    width: 100,
                    dataField: "applyQty",
                    needInput: false
                },
                {
                    name: "剩余数量",
                    width: 100,
                    dataField: "remainQty",
                    needInput: false
                },
            ];
            var materielFieldListForAdd = [{
                    name: "零件编号",
                    width: 150,
                    dataField: "materialsNo",
                    needInput: false
                },
                {
                    name: "零件中文名",
                    width: 150,
                    dataField: "materialsDes",
                    needInput: false
                },
                {
                    name: "单位",
                    width: 100,
                    dataField: "unit",
                    needInput: false
                },
                {
                    name: "默认储位",
                    width: 180,
                    dataField: "stockLocation",
                    needInput: false
                },
                {
                    name: "实际库存",
                    width: 120,
                    dataField: "enableNum",
                    clickFn: "alterReport",
                    needInput: false
                },
                {
                    name: "调入仓库库存",
                    width: 120,
                    dataField: "enableNumOther",
                    // clickFn: "alterReport",
                    needInput: false
                },
                {
                    name: "意向占用",
                    width: 100,
                    dataField: "intentionNum",
                    needInput: false
                },
                {
                    name: "发货占用",
                    width: 100,
                    dataField: "deliveryNum",
                    needInput: false
                },
                {
                    name: "申请数量",
                    width: 100,
                    dataField: "amount",
                    needInput: true,
                    needRequired: true
                },
                {
                    name: "备注",
                    width: 100,
                    dataField: "remark",
                    needInput: true,
                    needRequired: false
                }
            ];
            var materielFieldListForEdit = [{
                type: "",
                name: "序号",
                dataField: "rownum",
                width: 80,
                isShow: true,
                isFixed: false,
                toSort: false,
                sortType: ""
            },
            {
                name: "零件编号",
                width: 150,
                dataField: "materialsNo",
                needInput: false
            },
            {
                name: "零件中文名",
                width: 200,
                dataField: "materialsDes",
                needInput: false
            },
            {
                name: "单位",
                width: 100,
                dataField: "unit",
                needInput: false
            },
            {
                name: "默认储位",
                width: 180,
                dataField: "stockLocation",
                needInput: false
            },
            {
                name: "实际库存",
                width: 100,
                dataField: "enableNum",
                clickFn: "alterReport",
                needInput: false
            },
            {
                name: "调入仓库库存",
                width: 120,
                dataField: "enableNumOther",
                // clickFn: "alterReport",
                needInput: false
            },
            {
                name: "意向占用",
                width: 100,
                dataField: "intentionNum",
                needInput: false
            },
            {
                name: "发货占用",
                width: 100,
                dataField: "deliveryNum",
                needInput: false
            },
            {
                name: "申请数量",
                width: 120,
                dataField: "amount",
                needInput: true,
                needRequired: true
            },
            {
                name: "调出完成数",
                width: 120,
                dataField: "outAmount",
                needInput: false
            },
            {
                name: "调入完成数",
                width: 120,
                dataField: "inAmount",
                needInput: false
            },
            {
                name: "调出过账数",
                width: 120,
                dataField: "postOutAmount",
                needInput: false
            },
            {
                name: "调入过账数",
                width: 120,
                dataField: "postInAmount",
                needInput: false
            },
            {
                name: "领出零件凭证",
                width: 120,
                dataField: "voucherOutNo",
                input: false,
                inputType: ""
            },
            {
                name: "领入零件凭证",
                width: 120,
                dataField: "voucherInNo",
                input: false,
                inputType: ""
            },
            {
                name: "备注",
                width: 300,
                dataField: "remark",
                needInput: true,
                needRequired: false
            },
            {
              name: "标准交期",
              width: 150,
              dataField: "standDeliveryTime",
              isShow: true,
            },
            {
                name: "预计发货日期",
                dataField: "estimatedShippingDateShow",
                width: 130,
                isShow: true,
            },
        ]
            var materielFieldListAudit= [{
                type: "",
                name: "序号",
                dataField: "rownum",
                width: 80,
                isShow: true,
                isFixed: false,
                toSort: false,
                sortType: ""
            },
            {
                name: "零件编号",
                width: 150,
                dataField: "materialsNo",
                needInput: false
            },
            {
                name: "零件中文名",
                width: 200,
                dataField: "materialsDes",
                needInput: false
            },
            {
                name: "单位",
                width: 100,
                dataField: "unit",
                needInput: false
            },
            {
                name: "默认储位",
                width: 180,
                dataField: "stockLocation",
                needInput: false
            },
            {
                name: "实际库存",
                width: 100,
                dataField: "enableNum",
                clickFn: "alterReport",
                needInput: false
            },
            {
                name: "调入仓库库存",
                width: 120,
                dataField: "enableNumOther",
                // clickFn: "alterReport",
                needInput: false
            },
            {
                name: "意向占用",
                width: 100,
                dataField: "intentionNum",
                needInput: false
            },
            {
                name: "发货占用",
                width: 100,
                dataField: "deliveryNum",
                needInput: false
            },
            {
                name: "申请数量",
                width: 120,
                dataField: "amount",
                needInput: true,
                needRequired: true
            },
            {
                name: "调出完成数",
                width: 120,
                dataField: "outAmount",
                needInput: false
            },
            {
                name: "调入完成数",
                width: 120,
                dataField: "inAmount",
                needInput: false
            },
            {
                name: "调出过账数",
                width: 120,
                dataField: "postOutAmount",
                needInput: false
            },
            {
                name: "调入过账数",
                width: 120,
                dataField: "postInAmount",
                needInput: false
            },
            {
                name: "领出零件凭证",
                width: 120,
                dataField: "voucherOutNo",
                input: false,
                inputType: ""
            },
            {
                name: "领入零件凭证",
                width: 120,
                dataField: "voucherInNo",
                input: false,
                inputType: ""
            },
            {
                name: "备注",
                width: 300,
                dataField: "remark",
                needInput: true,
                needRequired: false
            },
            {
              name: "标准交期",
              width: 150,
              dataField: "standDeliveryTime",
              isShow: true,
            },
            {
                name: "预计发货日期",
                dataField: "estimatedShippingDateShow",
                width: 130,
                isShow: true,
            },
        ]
            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/regionAllot/export"),
                sectionParam: {
                    ids: []
                },
                allUrl: ybHttp.RequestUrl("device", "/regionAllot/exportAll")
            };
            $scope.orderObj = {
                headerInfo: {},
                detailList: []
            };
            $scope.stateList = [{
                    code: 0,
                    name: '未完成'
                },
                {
                    code: 1,
                    name: '部分完成'
                },
                {
                    code: 2,
                    name: '已完成'
                }
            ];
            $scope.tableConfig = {
                fixedWidth: $scope.isEN ? 650 : 300,
                scrollWidth: 2400,
                tableCol: [
                    {
                        type: "",
                        name: "调拨单号",
                        dataField: "allotOrder",
                        width: 170,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "区域调拨类型",
                        dataField: "allotTypeShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "调度员",
                        dataField: "dispatcherName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "移出仓库",
                        dataField: $scope.isWJ? "outLocationDesc":"outLocation",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "领出零件凭证",
                        dataField: "voucherOutNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "销售合同号",
                        dataField: "crmOrder",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "单据状态",
                        dataField: "statusDesc",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        name: "审核人",
                        dataField: "AuditName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "调出状态",
                        dataField: "outStateShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "领出过账状态",
                        dataField: "postingOutState",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "移入仓库",
                        dataField: "inLocationDesc",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "领入零件凭证",
                        dataField: "voucherInNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "调入状态",
                        dataField: "inStateShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "领入过账状态",
                        dataField: "postingInState",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "移动类型",
                        dataField: "moveType",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单时间",
                        dataField: "createDateShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单部门",
                        dataField: "deptName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单人",
                        dataField: "createName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "synSap",
                        name: "SAP同步状态",
                        dataField: "isSynSapShow",
                        width: 110,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewSapError",
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "SAP领出预留号",
                        dataField: "sapOutOrder",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "SAP领入预留号",
                        dataField: "sapInOrder",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "服务单号",
                        dataField: "serviceNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "CRM单号",
                        dataField: "crmOrder",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "synCRM",
                        name: "CRM同步状态",
                        dataField: "syncCrmFlagShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewCRMError",
                        toSort: true,
                        sortType: ""
                    },
                    {
                        name: "打印状态",
                        dataField: "isPrintName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "打印时间",
                        dataField: "printTimeShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "attach4sch",
                        name: "附件",
                        dataField: "fileAttach",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewAttach4sch",
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: $scope.isEN ? 610 : 500,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };
            $scope.tbConfDel = {
                scrollWidth: 2400,
                tableCol: [
                    {
                        type: "",
                        name: "调拨单号",
                        dataField: "allotOrder",
                        width: 170,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "区域调拨类型",
                        dataField: "allotTypeShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "调度员",
                        dataField: "dispatcherName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "移出仓库",
                        dataField: "outLocation",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "领出零件凭证",
                        dataField: "voucherOutNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "销售合同号",
                        dataField: "crmOrder",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "单据状态",
                        dataField: "statusDesc",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "调出状态",
                        dataField: "outStateShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "领出过账状态",
                        dataField: "postingOutState",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "移入仓库",
                        dataField: "inLocation",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "领入零件凭证",
                        dataField: "voucherInNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "调入状态",
                        dataField: "inStateShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "领入过账状态",
                        dataField: "postingInState",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "移动类型",
                        dataField: "moveType",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单时间",
                        dataField: "createDateShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单部门",
                        dataField: "deptName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单人",
                        dataField: "createName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "synSap",
                        name: "SAP同步状态",
                        dataField: "isSynSapShow",
                        width: 110,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewSapError",
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "SAP领出预留号",
                        dataField: "sapOutOrder",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "SAP领入预留号",
                        dataField: "sapInOrder",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "服务单号",
                        dataField: "serviceNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "CRM单号",
                        dataField: "crmOrder",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "synCRM",
                        name: "CRM同步状态",
                        dataField: "syncCrmFlagShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewCRMError",
                        toSort: true,
                        sortType: ""
                    },
                    {
                        name: "打印状态",
                        dataField: "isPrintName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        name: "打印时间",
                        dataField: "printTimeShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: $scope.isEN ? 610 : 500,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };
            $scope.materielTableConfig = {
                scrollWidth: 1390,
                tableCol: [{
                        type: "",
                        name: "序号",
                        dataField: "rownum",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        needInput: false
                    },
                    {
                        name: "零件中文名",
                        width: 200,
                        dataField: "materialsDes",
                        needInput: false
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        needInput: false
                    },
                    {
                        name: "默认储位",
                        width: 180,
                        dataField: "stockLocation",
                        needInput: false
                    },
                    {
                        name: "实际库存",
                        width: 100,
                        dataField: "enableNum",
                        clickFn: "alterReport",
                        needInput: false
                    },
                    {
                        name: "调入仓库库存",
                        width: 120,
                        dataField: "enableNumOther",
                        // clickFn: "alterReport",
                        needInput: false
                    },
                    {
                        name: "意向占用",
                        width: 100,
                        dataField: "intentionNum",
                        needInput: false
                    },
                    {
                        name: "发货占用",
                        width: 100,
                        dataField: "deliveryNum",
                        needInput: false
                    },
                    {
                        name: "申请数量",
                        width: 120,
                        dataField: "amount",
                        needInput: true,
                        needRequired: true
                    },
                    {
                        name: "调出完成数",
                        width: 120,
                        dataField: "outAmount",
                        needInput: false
                    },
                    {
                        name: "调入完成数",
                        width: 120,
                        dataField: "inAmount",
                        needInput: false
                    },
                    {
                        name: "调出过账数",
                        width: 120,
                        dataField: "postOutAmount",
                        needInput: false
                    },
                    {
                        name: "调入过账数",
                        width: 120,
                        dataField: "postInAmount",
                        needInput: false
                    },
                    {
                        name: "领出零件凭证",
                        width: 120,
                        dataField: "voucherOutNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "领入零件凭证",
                        width: 120,
                        dataField: "voucherInNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "备注",
                        width: 300,
                        dataField: "remark",
                        needInput: true,
                        needRequired: false
                    },
                    {
                      name: "标准交期",
                      width: 150,
                      dataField: "standDeliveryTime",
                      isShow: true,
                    },
                    {
                        name: "预计发货日期",
                        dataField: "estimatedShippingDateShow",
                        width: 130,
                        isShow: true,
                    },
                ]
            };

            $scope.materielDetailConfig = {
                scrollWidth: 1390,
                tableCol: [{
                        type: "",
                        name: "序号",
                        dataField: "rownum",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        needInput: false
                    },
                    {
                        name: "零件中文名",
                        width: 200,
                        dataField: "materialsDes",
                        needInput: false
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        needInput: false
                    },
                    {
                        name: "默认储位",
                        width: 180,
                        dataField: "stockLocation",
                        needInput: false
                    },
                    {
                        name: "实际库存",
                        width: 100,
                        dataField: "enableNum",
                        clickFn: "alterReport",
                        needInput: false
                    },
                    {
                        name: "调入仓库库存",
                        width: 120,
                        dataField: "enableNumOther",
                        clickFn: "alterReport",
                        needInput: false
                    },

                    {
                        name: "意向占用",
                        width: 100,
                        dataField: "intentionNum",
                        needInput: false
                    },
                    {
                        name: "发货占用",
                        width: 100,
                        dataField: "deliveryNum",
                        needInput: false
                    },
                    {
                        name: "申请数量",
                        width: 120,
                        dataField: "amount",
                        needInput: true,
                        needRequired: true
                    },
                    {
                        name: "调出完成数",
                        width: 120,
                        dataField: "outAmount",
                        needInput: false
                    },
                    {
                        name: "调入完成数",
                        width: 120,
                        dataField: "inAmount",
                        needInput: false
                    },
                    {
                        name: "调出过账数",
                        width: 120,
                        dataField: "postOutAmount",
                        needInput: false
                    },
                    {
                        name: "调入过账数",
                        width: 120,
                        dataField: "postInAmount",
                        needInput: false
                    },
                    {
                        name: "领出零件凭证",
                        width: 120,
                        dataField: "voucherOutNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "领入零件凭证",
                        width: 120,
                        dataField: "voucherInNo",
                        input: false,
                        inputType: ""
                    },
                    {
                      name: "标准交期",
                      width: 150,
                      dataField: "standDeliveryTime",
                      isShow: true,
                    },
                    {
                        name: "预计发货日期",
                        dataField: "estimatedShippingDateShow",
                        width: 130,
                        isShow: true,
                    },
                    {
                        name: "备注",
                        width: 300,
                        dataField: "remark",
                        needInput: true,
                        needRequired: false
                    }
                ]
            };

            $scope.inTbConf = {
                scrollWidth: 1100,
                tableCol: [{
                        type: "",
                        name: "序号",
                        dataField: "rownum",
                        width: 80,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        needInput: false
                    },
                    {
                        name: "零件中文名",
                        width: 200,
                        dataField: "materialsDes",
                        needInput: false
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        needInput: false
                    },
                    {
                        name: "默认储位",
                        width: 180,
                        dataField: "stockLocation",
                        needInput: false
                    },
                    {
                        name: "实际库存",
                        width: 100,
                        dataField: "enableNum",
                        clickFn: "alterReport",
                        needInput: false
                    },
                    {
                        name: "调入仓库库存",
                        width: 120,
                        dataField: "enableNumOther",
                        // clickFn: "alterReport",
                        needInput: false
                    },

                    {
                        name: "意向占用",
                        width: 100,
                        dataField: "intentionNum",
                        needInput: false
                    },
                    {
                        name: "发货占用",
                        width: 100,
                        dataField: "deliveryNum",
                        needInput: false
                    },
                    {
                        name: "申请数量",
                        width: 120,
                        dataField: "amount",
                        needInput: true,
                        needRequired: true
                    },
                    {
                        name: "调出完成数",
                        width: 120,
                        dataField: "outAmount",
                        needInput: false
                    },
                    {
                        name: "调入完成数",
                        width: 120,
                        dataField: "inAmount",
                        needInput: false
                    },
                    {
                        name: "调出过账数",
                        width: 120,
                        dataField: "postOutAmount",
                        needInput: false
                    },
                    {
                        name: "调入过账数",
                        width: 120,
                        dataField: "postInAmount",
                        needInput: false
                    },
                    {
                        name: "领出零件凭证",
                        width: 120,
                        dataField: "voucherOutNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "领入零件凭证",
                        width: 120,
                        dataField: "voucherInNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "储位",
                        width: 150,
                        dataField: "locationCode",
                        input: true,
                        inputType: "func"
                    },
                    {
                        name: "标准交期",
                        width: 150,
                        dataField: "standDeliveryTime",
                        isShow: true,
                    },
                    {
                        name: "预计发货日期",
                        dataField: "estimatedShippingDateShow",
                        width: 130,
                        isShow: true,
                    },
                    {
                        name: "备注",
                        width: 300,
                        dataField: "remark",
                        needInput: true,
                        needRequired: false
                    }
                ]
            };
            $scope.forWardTableConfig = {
                fixedWidth: 180,
                scrollWidth: 1660,
                tableCol: [
                    {
                        type: "",
                        name: "单据编号",
                        dataField: "billNo",
                        width: 170,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "供货商名称",
                        dataField: "supplierOrgName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "申请机构名称",
                        dataField: "applyOrgName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "状态",
                        dataField: "statusShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "创建状态",
                        dataField: "createStatusShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "供货商出库仓库编号",
                        dataField: "outWarehouseCode",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "供货商入库仓库编号",
                        dataField: "inWarehouseCode",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "创建人名称",
                        dataField: "createName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "创建时间",
                        dataField: "createDateShow",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: false,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "更新人名称",
                        dataField: "updateNameShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "更新时间",
                        dataField: "auditDateShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核人名称",
                        dataField: "auditName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核时间",
                        dataField: "auditDate",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "审核信息",
                        dataField: "auditMessage",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "备注",
                        dataField: "remark",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: $scope.isEN ? 610 : 500,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };


            $scope.tabFlag = {};

            var btnPermissionCode = {
                stockAllocationAdd: window.ActionCode.stockAllocationAdd,
                stockAllocationEdit: window.ActionCode.stockAllocationEdit,
                stockAllocationEditTJ: window.ActionCode.stockAllocationEditTJ,
                stockAllocationDel: window.ActionCode.stockAllocationDel,
                stockAllocationExport: window.ActionCode.stockAllocationExport,
                stockAllocationPrint: window.ActionCode.stockAllocationPrint,
                stockAllocationObligateAdd: window.ActionCode.stockAllocationObligateAdd,
                stockAllocationObligatePosting: window.ActionCode.stockAllocationObligatePosting,
                stockAllocationAudit: window.ActionCode.stockAllocationAudit,
                stockAllocationAdjust: window.ActionCode.stockAllocationAdjust,
                stockAllocationOut: window.ActionCode.stockAllocationOut,
                stockAllocationIn: window.ActionCode.stockAllocationIn,
                stockAllocationCRM: window.ActionCode.stockAllocationCRM,
                stockAllocationFinishOut: window.ActionCode.stockAllocationFinishOut,
                stockAllocationAuditRevo: window.ActionCode.stockAllocationAuditRevo
            };

            $scope.btnPermission = {
                stockAllocationAdd: true,
                stockAllocationEdit: true,
                stockAllocationEditTJ: true,
                stockAllocationDel: true,
                stockAllocationExport: true,
                stockAllocationPrint: true,
                stockAllocationObligateAdd: true,
                stockAllocationObligatePosting: true,
                stockAllocationAudit: true,
                stockAllocationAdjust: true,
                stockAllocationOut: true,
                stockAllocationIn: true,
                stockAllocationCRM: true,
                stockAllocationFinishOut: true,
                stockAllocationAuditRevo: true
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    billFixedWidth: {
                        left: $scope.tableConfig.fixedWidth + "px"
                    },
                    forWardBillFixedWidth: {
                        left: $scope.forWardTableConfig.fixedWidth + "px"
                    },
                    scrollLeftWidth: { width: $scope.tableConfig.fixedWidth + "px" },
                };
            };

            function initData() {
                $scope.tabFlag = {};
                $scope.detailInfo = {
                    crucialDevice: 0,
                    entranceDevice: 0
                };
                $scope.materielTableConfig.tableCol = materielFieldList;
                $scope.orderObj = {
                    headerInfo: {},
                    detailList: []
                };
                $scope.markInfo.allCheckedMaterial = false;
                $scope.toolbarConfig.showMateriel = false;
            }

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        initData();
                        getDataList();
                        $scope.submitted = false;
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    default:
                        break;
                }
            };

            function getDataList(curPage) {
                $scope.markInfo = {
                    allCheckedBill: false,
                    allCheckedMaterial: false,
                    curRow: -1
                };
                $scope.exportParam.sectionParam.ids = [];
                var service = "device";
                var reqUrl = "/regionAllot/list";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = $scope.condition;
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    console.log(resp.value.list);
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.createDateShow = $filter("YbDate")(item.createDate, 'yyyy-MM-dd HH:mm:ss');
                        item.outStateShow = $filter("allotState")(item.outState);
                        item.inStateShow = $filter("allotState")(item.inState);
                        item.isSynSapShow = $filter("ProgressStatus")(item.isSynSap, "sap");
                        item.syncCrmFlagShow = $filter("ProgressStatus")(item.syncCrmFlag, "sap");
                        item.postingOutState = $filter("ProgressStatus")(item.postOutStatus, "posting");
                        item.postingInState = $filter("ProgressStatus")(item.postInStatus, "posting");
                        item.printTimeShow = $filter("YbDate")(item.printTime, "yyyy-MM-dd HH:mm");
                        if (!!item.allotType) {
                            for (var i in $scope.allotTypeList) {
                                if (item.allotType == $scope.allotTypeList[i].code) {
                                    item.allotTypeShow = $scope.allotTypeList[i].name;
                                }
                            }
                        }
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                    return resp.value.list;
                });
            }
            function getDataListFor(curPage) {
                $scope.markInfo = {
                    allCheckedBill: false,
                    allCheckedMaterial: false,
                    curRow: -1
                };
                $scope.exportParam.sectionParam.ids = [];
                var service = "device";
                var reqUrl = "/forwardAllotApply/createRegionAllotList";
                var param = {};
                param.pageSize = $scope.pageInfoFor.pageSize;
                if (!!curPage) {
                    $scope.pageInfoFor.curPage = curPage;
                }
                param.pageNum = $scope.pageInfoFor.curPage;
                param.filters = $scope.conditionFor;
                param.filters.billNoList =  $filter("replaceNArray")(param.filters.billNoList)
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.createDateShow = $filter("YbDate")(item.createDate, 'yyyy-MM-dd HH:mm:ss');
                        item.updateNameShow = $filter("YbDate")(item.updateName, 'yyyy-MM-dd HH:mm:ss');
                        item.auditDateShow = $filter("YbDate")(item.auditDate, 'yyyy-MM-dd HH:mm:ss');
                        item.statusShow = $filter("ProgressStatus")(item.status, "applyOrgNameStatus");
                        item.createStatusShow = $filter("ProgressStatus")(item.createStatus, "createdStatus");
                    });
                    $scope.pageInfoFor.totalRows = resp.value.total;
                    $scope.pageInfoFor.totalPages = resp.value.pages;
                    $scope.dataListFor = resp.value.list;
                    return resp.value.list;
                });
            }
            $scope.selectRow = function (index) {
                $scope.markInfo.curRow = index
            };

            $scope.tdClick = function (item, fnType, type) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(item, type);
                        break;
                    case "viewSapError":
                        viewSapError(item);
                        break;
                    case "viewCRMError":
                        viewCRMError(item);
                        break;
                    case "alterReport":
                        alterReport(item);
                        break;
                    case "intentionDetail":
                        intentionDetail(item);
                        break;
                    case "deliveryDetail":
                        deliveryDetail(item);
                        break;
                    case "viewAttach4sch":
                        viewAttach4sch(item);
                        break;
                    default:
                        break;
                }
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.switchDatePicker = function (index) {
                $scope.datePickerFlag = [false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.searchFor = function (curpage) {
                getDataListFor(curpage)
            };
            $scope.delHistory = function (curPage) {
                $scope.tabFlag.type = 8;
                $scope.changeTab(8);
                var service = "device";
                var reqUrl = "/regionAllot/list"
                var param = {}
                param.pageSize = $scope.pageInfoDel.pageSize;
                if (!!curPage) {
                    $scope.pageInfoDel.curPage = curPage;
                }
                param.pageNum = $scope.pageInfoDel.curPage;
                param.filters = angular.copy($scope.condition);
                param.filters.isProcessing = null;
                param.filters.isDel = 1;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        if (item.type === 0) {
                            item.statusShow = $filter("ProgressStatus")(item.status, "inDepot");
                        }
                        if (item.type === 1) {
                            item.statusShow = $filter("ProgressStatus")(item.status, "outDepot");
                        }
                        item.sapStatusShow = $filter("ProgressStatus")(item.sapStatus, "sap");
                        item.postOutStatus = $filter("ProgressStatus")(item.postOutStatus, "posting");
                        item.postInStatus = $filter("ProgressStatus")(item.postInStatus, "posting");
                        item.receiptStatusShow = $filter("ProgressStatus")(item.isReceipt, "receiptState");
                        item.auditStatusShow = $filter("AuditStatus2")(item.auditStatus);
                        item.auditDateShow = $filter("YbDate")(item.auditDate, "yyyy-MM-dd HH:mm:ss");
                        item.printTimeShow = $filter("YbDate")(item.printTime, "yyyy-MM-dd HH:mm");
                    });
                    $scope.pageInfoDel.totalRows = resp.value.total;
                    $scope.pageInfoDel.totalPages = resp.value.pages;
                    $scope.dataDelList = resp.value.list;
                });
            };
            $scope.reset = function () {
                $scope.condition = {};
            };
            $scope.resetFor = function () {
                $scope.conditionFor = {};
            };
            function alterReport(item) {
                var param = {
                    materialsNo: item.materialsNo
                };
                ybWidget.StorageReport(param);
            }

            $scope.finishOut = function (allotOrder, detailId, materialNo) {
                var service = "device";
                var reqUrl = "/regionAllot/manualFinishOut";
                ybWidget.ShowMessage("确定要结单吗？", MESG_TYPE.Ask).then(function () {
                    var param = {
                        billNo: allotOrder,
                        materialsNo: materialNo
                    };
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        if (!!detailId) {
                            getDetail({
                                id: detailId
                            }).then(function (data) {
                                if (!data) {
                                    return;
                                }
                                $scope.detailInfo = data;
                            });
                        }
                        getDataList();
                    })
                });
            };

            function intentionDetail(item) {
                var param = {
                    materialsNo: item.materialsNo
                };
                ybWidget.IntentionDetail(param);
            }

            function deliveryDetail(item) {
                var param = {
                    materialsNo: item.materialsNo,
                    warehouseCode: $scope.orderObj.headerInfo.outLocation
                };
                ybWidget.DeliveryDetail(param);
            }

            function getBillIds() {
                $scope.exportParam.sectionParam.ids = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.ids.push(item.id);
                    }
                });
            }

            $scope.selectSingle = function (item, list, type) {
                if (!item.isChecked) {
                    $scope.markInfo["allChecked" + type] = false;
                } else {
                    if (!checkAll(list)) {
                        $scope.markInfo["allChecked" + type] = false;
                    } else {
                        $scope.markInfo["allChecked" + type] = true;
                    }
                }
                getBillIds();
            };

            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectAll = function (list, type) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfo["allChecked" + type];
                });
                getBillIds();
            };

            $scope.printBill = function (item) {
                var id = item.id;
                var billIds = [];
                billIds.push(id);
                var param = {
                    billId: billIds,
                    printType: "DepotAllocation",
                    recordPrint: {
                        billNo: item.allotOrder
                    }
                };
                ybWidget.SetIsPrintOrPreview(param).then(function() {
                    getDataList();
                });
            };
            $scope.batchPrint = function () {
                var billIds = [];
                var billNos = [];
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    if (!!$scope.dataList[i].isChecked) {
                        billIds.push($scope.dataList[i].id);
                        billNos.push($scope.dataList[i].allotOrder);
                    }
                }
                if (billIds.length === 0) {
                    ybWidget.ShowMessage('请选择需要打印的行');
                    return;
                }
                var param = {
                    printType: "DepotAllocation",
                    cusInterface: '/regionAllot/itemList',
                    cusParam: { ids: billIds },
                    isBatchPrint: true,
                    recordPrint: {
                        billNo: billNos.join(',')
                    }
                };
                ybWidget.SetIsPrintOrPreview(param).then(function() {
                    getDataList();
                });
            };

            $scope.printBill4Details = function (item) {
                var param = {
                    printType: "DepotAllocation",
                    cusInterface: '/regionAllot/itemDetail',
                    cusParam: {
                        id: $scope.orderObj.headerInfo.id,
                        detailIds: [item.id]
                    },
                    recordPrint: {
                        billNo: $scope.orderObj.headerInfo.allotOrder
                    }
                };
                ybWidget.SetIsPrintOrPreview(param).then(function() {
                    getDataList();
                });
            };

            $scope.batchPrint4Details = function () {
                const selectedIds4Detail = $scope.orderObj.detailList.filter(d => d.isChecked).map(dm => dm.id);
                if (selectedIds4Detail.length === 0) {
                    ybWidget.ShowMessage('请选择需要打印的行');
                    return;
                }

                var param = {
                    printType: "DepotAllocation",
                    cusInterface: '/regionAllot/itemDetail',
                    cusParam: {
                        id: $scope.orderObj.headerInfo.id,
                        detailIds: selectedIds4Detail
                    },
                    recordPrint: {
                        billNo: $scope.orderObj.headerInfo.allotOrder
                    }
                };
                ybWidget.SetIsPrintOrPreview(param).then(function() {
                    getDataList();
                });
            };

            $scope.addApply = function () {
                $scope.tabFlag.type = 1;
                $scope.orderObj.headerInfo.createDate = +new Date();
                $scope.orderObj.headerInfo.moveType = '311';
                $scope.materielTableConfig.scrollWidth = 600;
                $scope.materielTableConfig.tableCol = materielFieldListForAdd;
                setUserInfo();
                $scope.changeTab(2);
            };
            $scope.makeAllotOrder = function(item) {
                setUserInfo();
                getDetailFor(item)
                $scope.materielTableConfig.tableCol = angular.copy(materielFieldList);
                $scope.materielTableConfig.tableCol.unshift(
                    {
                        name: "前移库调拨单号",
                        width: 150,
                        dataField: "forwardAllotNo",
                        needInput: false
                    }
                )
                $scope.changeTab(2);
            }

            function getDetailFor(item) {
                var param = {
                    id: item.id
                };
                var reqUrl = '/forwardAllotApply/createRegionAllotDetail' // 正常查询详情
                return ybHttp.Get('device', reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    $scope.orderObj.headerInfo = resp.value.headerInfo
                    $scope.orderObj.detailList = resp.value.materialList
                    console.log($scope.orderObj.detailList)
                    // 映射数据
                    $scope.orderObj.headerInfo.outLocation = resp.value.headerInfo.outWarehouseCode
                    $scope.orderObj.headerInfo.inLocation = resp.value.headerInfo.inWarehouseCode
                    $scope.orderObj.headerInfo.forwardAllotNo = resp.value.headerInfo.billNo
                    $scope.orderObj.headerInfo.moveType = '311'
                    angular.forEach(resp.value.materialList, function (item,index) {
                        item.rownum = index + 1
                        item.materialsDes = item.materialName;
                        item.materialsNo = item.materialNo;
                        item.amount =  angular.copy(item.remainQty)
                        item.estimatedShippingDateShow = $filter("YbDate")(item.estimatedShippingDate, 'yyyy-MM-dd HH:mm:ss');
                    });
                });
            }
            $scope.forWardAllotAdd = function () {
                $scope.changeTab(10);
                getDataListFor(1)
            }
            function setUserInfo() {
                $scope.orderObj.headerInfo.dispatcherName = $scope.curUser.name;
                $scope.orderObj.headerInfo.deptId = $scope.curUser.deptId;
                $scope.orderObj.headerInfo.deptName = $scope.curUser.deptName;
            }

            $scope.selectWarehouse = function (type, selectedId) {
                ybWidget.WarehouseUsingSelector({
                    selectedId: selectedId,
                    needPermit: true
                }).then(function (data) {
                    if (type == 'in') {
                        if (!!$scope.orderObj.headerInfo.inLocation && (data.warehouseCode !== $scope.orderObj.headerInfo.inLocation)) {
                            $scope.orderObj.headerInfo.inArea = "";
                            $scope.orderObj.headerInfo.sapInArea = "";
                        }
                        $scope.orderObj.headerInfo.inLocation = data.warehouseCode;
                        $scope.orderObj.headerInfo.inLocationDesc = data.description;
                    }
                    if (type == 'out') {
                        if (!!$scope.orderObj.headerInfo.outLocation && (data.warehouseCode !== $scope.orderObj.headerInfo.outLocation)) {
                            $scope.orderObj.headerInfo.outArea = "";
                            $scope.orderObj.headerInfo.sapOutArea = "";
                        }
                        $scope.orderObj.headerInfo.outLocation = data.warehouseCode;
                        $scope.orderObj.headerInfo.outLocationDesc = data.description;
                        // 实时更新库存数量
                        findDeliveryNum()
                    }
                })
            };

            $scope.clearWarehouse = function (type) {
                if (type == 'in') {
                    $scope.orderObj.headerInfo.inLocation = "";
                    $scope.orderObj.headerInfo.inArea = "";
                    $scope.orderObj.headerInfo.sapInArea = "";
                }
                if (type == 'out') {
                    $scope.orderObj.headerInfo.outLocation = "";
                    $scope.orderObj.headerInfo.outArea = "";
                    $scope.orderObj.headerInfo.sapOutArea = "";
                    $scope.clearLocCode();
                    // 实时更新库存数量
                    findDeliveryNum()
                }
            };

            $scope.selectArea = function (type, areaCode) {
                if (type === 'out' && !$scope.orderObj.headerInfo.outLocation) {
                    ybWidget.ShowToaster('error', '请选择调出仓库');
                    return;
                }
                if (type === 'in' && !$scope.orderObj.headerInfo.inLocation) {
                    ybWidget.ShowToaster('error', '请选择调入仓库');
                    return;
                }
                var param = {};
                param.warehouseCode = type === "in" ? $scope.orderObj.headerInfo.inLocation : $scope.orderObj.headerInfo.outLocation;
                param.isWarehouse = $scope.orderObj.headerInfo.inLocation === $scope.orderObj.headerInfo.outLocation;
                param.selectedId = areaCode;
                if($scope.isNJ){
                    if (type === 'out'){
                        param.sapAreaCode =  $scope.orderObj.headerInfo.sapInArea;
                        param.oppositeAreaCode =  $scope.orderObj.headerInfo.inArea;
                    }else if(type === 'in'){
                        param.sapAreaCode =  $scope.orderObj.headerInfo.sapOutArea;
                        param.oppositeAreaCode =  $scope.orderObj.headerInfo.outArea;
                    }
                }
                ybWidget.DepotAreaSelector(param).then(function (data) {
                    if (type === 'out') {
                        $scope.orderObj.headerInfo.outArea = data.areaCode;
                        $scope.orderObj.headerInfo.sapOutArea = data.sapCode;
                        // 实时更新库存数量
                        findDeliveryNum();
                        // 查询所选零件的默认储位
                        var nos = [];
                        angular.forEach($scope.orderObj.detailList, function (item) {
                            nos.push(item.materialsNo);
                        });
                        if (nos.length > 0) {
                            var param = {
                                warehouseCode: $scope.orderObj.headerInfo.outLocation,
                                areaCode: data.areaCode,
                                materialsNos: nos
                            };
                            ybHttp.Post("device", "/materials/findDefaultLocation", param).then(function (resp) {
                                angular.forEach($scope.orderObj.detailList, function (item) {
                                    // 选择库区后 展示零件的默认储位
                                    item.stockLocation = resp.value[item.materialsNo];
                                });
                            })
                        }
                    }
                    if (type === 'in') {
                        $scope.orderObj.headerInfo.inArea = data.areaCode;
                        $scope.orderObj.headerInfo.sapInArea = data.sapCode;
                    }
                })
            };

            $scope.clearArea = function (type) {
                if (type === 'out') {
                    $scope.orderObj.headerInfo.outArea = "";
                    $scope.orderObj.headerInfo.sapOutArea = "";
                    $scope.clearLocCode();
                    // 实时更新库存数量
                    findDeliveryNum();
                }
                if (type === 'in') {
                    $scope.orderObj.headerInfo.inArea = "";
                    $scope.orderObj.headerInfo.sapInArea = ""
                }
            };

            $scope.clearLocCode = function () {
                angular.forEach($scope.orderObj.detailList, function (item) {
                    // 清除库区后同时清除默认储位
                    item.stockLocation = "";
                });
            }

            // 实时更新库存数量
            function findDeliveryNum() {
              if ($scope.orderObj.detailList.length <= 0) {
                return;
              }

              var service = "device";
              var reqUrl = "/materials/findDeliveryNum";
              var param = {};
              param.warehouseCode = $scope.orderObj.headerInfo.outLocation;
              param.areaCode = $scope.orderObj.headerInfo.outArea;
              param.materialsVOS = $scope.orderObj.detailList.map(item => ({materialsNo: item.materialsNo}))
              return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                  console.log(resp.value);
                  if (resp.code !== 0) {
                      ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                      return false;
                  }
                  if (!resp.value) {
                      return;
                  }
                  angular.forEach($scope.orderObj.detailList, function (item) {
                      angular.forEach(resp.value.materialsVOS, function (itemDetail) {
                          if (item.materialsNo === itemDetail.materialsNo) {
                              item.deliveryNum = itemDetail.deliveryNum;
                              item.enableNum = itemDetail.enableNum;
                            }
                      });
                  });
              }).catch(err => {
                console.log(err);
              });
            }

            $scope.delApply = function (id) {
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function (data) {
                    var service = "device";
                    var reqUrl = "/regionAllot/remove";
                    var param = {
                        ids: []
                    };
                    param.ids.push(id);
                    ybHttp.Post(service, reqUrl, param.ids).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                })
            };

            $scope.AuditRevo = function (id) {
                ybWidget.ShowMessage("确定要撤销审核吗？", MESG_TYPE.Ask).then(function (data) {
                    var service = "device";
                    var reqUrl = "/regionAllot/auditRevoke";
                    var param = {
                        headerInfo:{
                            id: id
                        }
                    };
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                })
            };
            function getDetail(item, type) {
                var param = {
                    id: item.id
                };
                if (type) {
                    var reqUrl = '/regionAllot/itemWithDel' // 删除详情
                }else {
                    var reqUrl = '/regionAllot/item' // 正常查询详情
                }
                return ybHttp.Get('device', reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    angular.forEach(resp.value.detailList, function (item) {
                        item.materialsDes = item.materialName;
                        item.materialsNo = item.materialNo;
                        checkItemStockStatus(item, item.amount);
                    });
                    if (!!resp.value.headerInfo.allotType) {
                        for (var item in $scope.allotTypeList) {
                            if (resp.value.headerInfo.allotType == $scope.allotTypeList[item].code) {
                                resp.value.headerInfo.allotTypeShow = $scope.allotTypeList[item].name;
                            }
                        }
                    }
                    return $scope.orderObj = resp.value;
                });
            }

            $scope.editApply = function (item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.tabFlag.type = 2;
                    angular.forEach(data.detailList, function (item) {
                        item.estimatedShippingDateShow = $filter("YbDate")(item.estimatedShippingDate, 'yyyy-MM-dd HH:mm:ss');
                    })
                    $scope.orderObj = data;
                    $scope.materielTableConfig.tableCol = materielFieldListForEdit
                    $scope.changeTab(3);
                });
            };
            $scope.auditBill = function (item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.materielTableConfig.tableCol = materielFieldListAudit
                    angular.forEach(data.detailList, function (item) {
                      item.estimatedShippingDateShow = $filter("YbDate")(item.estimatedShippingDate, 'yyyy-MM-dd HH:mm:ss');
                    })
                    $scope.orderObj = data;
                    console.log(data);
                    $scope.changeTab(4);
                });
            };

            $scope.synCRM = function (syncType, billId) {
                var service = "device";
                var reqUrl = "/regionAllot/syncCrm";
                var billIds = [];
                if (syncType === "single") {
                    billIds.push(billId);
                }
                if (syncType === "batch") {
                    for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                        if (!!$scope.dataList[i].isChecked) {
                            if ($scope.dataList[i].syncCrmFlag === 1) { //!$scope.dataList[i].syncCrmFlag ||
                                ybWidget.ShowMessage('请选择未同步或同步失败的数据进行CRM同步！');
                                return;
                            }
                            billIds.push($scope.dataList[i].id);
                        }
                    }
                }
                if (billIds.length === 0) {
                    ybWidget.ShowMessage('请选择需要同步的行');
                    return;
                }
                ybWidget.ShowMessage("确定要同步吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Post(service, reqUrl, billIds).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                });
            };

            $scope.adjustBill = function (item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.orderObj = data;
                    $scope.materielTableConfig.tableCol = materielFieldListAudit
                    // 审核通过时
                    if ($scope.orderObj.headerInfo.billStatus == 2) {
                      angular.forEach($scope.orderObj.detailList, function (item) {
                          item.deliveryNum = item.deliveryNum - item.amount;
                      });
                    }
                    angular.forEach($scope.orderObj.detailList, function (item) {
                        item.estimatedShippingDateShow = $filter("YbDate")(item.estimatedShippingDate, 'yyyy-MM-dd HH:mm:ss');
                    });
                    $scope.changeTab(5);
                });
            };

            function viewDetail(item, type) {
                getDetail(item, type).then(function (data) {
                    if (!data) {
                        return;
                    }
                    angular.forEach(data.detailList, function (item) {
                      item.estimatedShippingDateShow = $filter("YbDate")(item.estimatedShippingDate, 'yyyy-MM-dd HH:mm:ss');
                    });
                    $scope.orderObj = data;
                    if (type) {
                        $scope.changeTab(9);
                    }else {
                        $scope.changeTab(1);
                    }

                });
            }

            function viewSapError(item) {
                ybWidget.ShowMessage(item.sapErrorMsg, MESG_TYPE.Note);
            }

            function viewCRMError(item) {
                ybWidget.ShowMessage(item.syncCrmMsg, MESG_TYPE.Note);
            }

            /* wangcan:获取区域调拨数据字典 */
            function getWarehouseType() {
                var service = "device";
                var reqUrl = "/serviceBasicDataAgent/searchList";
                var param = {
                    pCode: "ALLOT_TYPE"
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.allotTypeList = resp.value;
                });
            }

            $scope.selMateriel = function (e) {
                if (!!$scope.toolbarConfig.showMateriel) {
                    e.stopPropagation();
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig.showMateriel = true;
                        EventBus.Publish("getMaterial");
                    });
                }
            };

            $scope.importMateriel = function () {
                var param = {
                    name: "零件",
                    templateReqService: "device",
                    templateReqUrl: "/regionAllot/download",
                    importReqService: "device",
                    importReqUrl: "/regionAllot/import",
                    importErrorUrl: "",
                    warehouseCode: $scope.orderObj.headerInfo.outLocation,
                    areaCode: $scope.orderObj.headerInfo.outArea
                };
                ybWidget.ImportFile(param).then(function (data) {
                    angular.forEach(data, function (item) {
                        item.isChecked = false;
                        item.materialsDes = item.materialName;
                        item.materialsNo = item.materialNo;
                    });
                    $scope.orderObj.detailList = [];
                    $scope.orderObj.detailList = angular.copy(data);
                });
            };

            $scope.delMateriel = function (item, index) {
                ybWidget.ShowMessage("确定要删除该记录吗？", MESG_TYPE.Ask).then(function () {
                    $scope.orderObj.detailList.splice(index, 1);
                    EventBus.Publish("setMaterial", item.materialsNo);
                });
            };
            $scope.obligate = function (item) {
                item.obligateDisabled = true;
                var service = "device";
                var reqUrl = "/warehouseInventory/createObligateOrder";
                var param = {};
                param.id = item.id;
                param.businessOrder = item.allotOrder;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        item.obligateDisabled = false;
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    getDataList();
                });
            };

            $scope.searchDispatch = function () {
                var param = {
                    name: "区域调拨调度员",
                    defaultRoleName: '',
                    type: 'staffByWorkspace',
                    supplierOrgId: $scope.curUser.spaceId
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.orderObj.headerInfo.dispatcherName = data.name;
                    $scope.orderObj.headerInfo.dispatcherId = data.userId;
                })
            }

            $scope.posting = function (item, inOut, materialsNo) {
                ybWidget.ShowMessage("确定要过账吗？", MESG_TYPE.Ask).then(function () {
                    var postingType = inOut === 1 ? "Out" : "In";
                    item["posting" + postingType + "Disabled"] = true;
                    var service = "device";
                    var reqUrl = "/warehouseInventory/obligatePosting";
                    var param = {};
                    param.businessOrder = item.allotOrder;
                    param.materialsNo = materialsNo;
                    param.inOut = inOut;
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            item["posting" + postingType + "Disabled"] = false;
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        if (!!item.id) {
                            getDetail(item).then(function (data) {
                                if (!data) {
                                    return;
                                }
                                $scope.orderObj = data;
                            });
                        }
                        getDataList();
                    });
                }, function () {});
            };

            $scope.deliveryRevoke = function (item, materialsNo) {
                ybWidget.ShowMessage("确定要撤回吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/warehouseInventory/deliveryRevoke";
                    var param = {
                        businessOrder: item.allotOrder,
                        materialsNo: materialsNo ? materialsNo : null
                    };
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        if (!!item.id) {
                            getDetail(item).then(function (data) {
                                if (!data) {
                                    return;
                                }
                                $scope.orderObj = data;
                            });
                        }
                        getDataList();
                    });
                }, function () {});
            };

            $scope.batchDelMateriel = function () {
                var selectedCount = 0;
                for (var i = 0, len = $scope.orderObj.detailList.length; i < len; i++) {
                    if (!!$scope.orderObj.detailList[i].isChecked) {
                        selectedCount++;
                    }
                }
                if (!selectedCount) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                ybWidget.ShowMessage("确定要删除选中的记录吗？", MESG_TYPE.Ask).then(function () {
                    for (var i = $scope.orderObj.detailList.length - 1; i >= 0; i--) {
                        if (!!$scope.orderObj.detailList[i].isChecked) {
                            if ((!!$scope.orderObj.detailList[i].inState && $scope.orderObj.detailList[i].inState !== 0) || (!!$scope.orderObj.detailList[i].outState && $scope.orderObj.detailList[i].outState !== 0)) {
                                ybWidget.ShowMessage("只能删除未调出的零件", MESG_TYPE.Warn);
                                return;
                            }
                            $scope.orderObj.detailList.splice(i, 1);
                        }
                    }
                    if ($scope.orderObj.detailList.length === 0) {
                        $scope.markInfo.allCheckedMaterial = false;
                    }
                    EventBus.Publish("setMaterial");
                });
            };

            $scope.auditPurchase = function (type, headerInfo, message) {
                var service = "device";
                var reqUrl = "/regionAllot/auditRefused";
                var param = {
                    headerInfo: {
                        id: headerInfo.id,
                        auditMessage: message,
                    }

                };
                if (type === "refuse" && !message) {
                    ybWidget.ShowMessage('请输入审核意见');
                    $scope.submitted = true;
                    return;
                }
                if (type === "pass") {
                    reqUrl = "/regionAllot/auditPass";
                }
                if (type === "refuse") {
                    reqUrl = "/regionAllot/auditRefused";
                }

                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    $scope.orderObj.headerInfo.note = "";
                });
            };

            $scope.checkQty = function (item) {
                item.qtyErr = false;
                item.qtyAdjustErr = false;
                item.qtyAdjustErr2 = false;
                if (!item.amount || parseFloat(item.amount) <= 0) {
                    item.qtyErr = true;
                    return;
                }
                if (item.amount > item.oldAmount) {
                    item.qtyAdjustErr = true;
                    return;
                }
                if (item.amount < item.outAmount) {
                    item.qtyAdjustErr2 = true;
                    return;
                }
                checkItemStockStatus(item, item.amount);
            };

            $scope.checkQtyForAdd = function (item) {
                item.qtyErr = false;
                if (!item.amount || parseFloat(item.amount) <= 0) {
                    item.qtyErr = true;
                    return;
                }
                if (item.amount > (item.planAmount - item.allotAmount)) {
                    item.amount = item.planAmount - item.allotAmount;
                    return;
                }
                if (item.remainQty && item.amount > item.remainQty) {
                    item.amount = item.remainQty
                    ybWidget.ShowMessage("申请数量不可大于剩余数量", MESG_TYPE.Error);
                }
            };
            $scope.handleAudit = function(type, ids, msg) {
                var service = "device";
                var reqUrl = "";
                var param = {
                    ids: ids || [$scope.auditId]
                };

                var msgStr = msg || $scope.auditMessage.value;
                if (type == 1) {
                    // 通过
                    reqUrl = "/regionAllot/commonAuditPass"
                } else if (type == 2) {
                    // 拒绝
                    if (!msgStr) {
                        ybWidget.ShowMessage("请填写审核意见", MESG_TYPE.Error);
                        return
                    }
                    reqUrl = "/regionAllot/commonAuditReject"
                }
                param.auditRemark = msgStr;
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    getDataList();
                    $scope.changeTab(0);
                });
            };
            $scope.auditBillBatch = function () {
                $scope.auditMessage = {};
                var ids = [];
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    if (!!$scope.dataList[i].isChecked) {
                        ids.push($scope.dataList[i].id);
                    }
                }
                if (ids.length === 0) {
                    ybWidget.ShowMessage('请正确选择需要审核的行');
                    return;
                }
                ybWidget.AuditMsg({
                    passCb: function(val) {
                        return $scope.handleAudit(1, ids, val)
                    },
                    refuseCb: function(val) {
                        return $scope.handleAudit(2, ids, val)
                    }
                })
            };
            function checkItemStockStatus(item, currentQty) {
                UserContextService.SetStockStatusFlag(item, currentQty);
            }

            $scope.showQtyTip = function (item) {
                if (!!item.qtyStockErr) {
                    item.showStockErr = true;
                }
            };
            $scope.hideQtyTip = function (item) {
                item.showStockErr = false;
            };

            $scope.saveData = function (type, invalid) {
                if (!invalid) {
                    $scope.submitted = true;
                    return;
                }
                var listValid = true;
                var service = "device";
                var reqUrl = "/regionAllot/add";
                if (!!$scope.orderObj.headerInfo.allotOrder) {
                    reqUrl = "/regionAllot/update";
                }
                if (type === "adjust") {
                    reqUrl = "/regionAllot/adjust";
                }

                for (var i = 0, len = $scope.orderObj.detailList.length; i < len; i++) {
                    $scope.orderObj.detailList[i].materialName = $scope.orderObj.detailList[i].materialsDes;
                    $scope.orderObj.detailList[i].materialNo = $scope.orderObj.detailList[i].materialsNo;
                    if (!$scope.orderObj.detailList[i].amount || parseFloat($scope.orderObj.detailList[i].amount) <= 0) {
                        listValid = false;
                        $scope.orderObj.detailList[i].qtyErr = true;
                        $scope.orderObj.detailList[i].showStockErr = true;
                        break;
                    }
                    if($scope.orderObj.detailList[i].oldAmount === undefined )
                    {
                        if (type === "adjust" && $scope.orderObj.detailList[i].amount === 0) {
                            listValid = false;
                            $scope.orderObj.detailList[i].qtyAdjustErr = true;
                            break;
                        }
                        $scope.orderObj.detailList[i].inAmount =0;
                        $scope.orderObj.detailList[i].oldAmount =0;
                        $scope.orderObj.detailList[i].outAmount =0;

                    }
                    else{
                    if (type === "adjust" && $scope.orderObj.detailList[i].amount > $scope.orderObj.detailList[i].oldAmount) {
                        listValid = false;
                        $scope.orderObj.detailList[i].qtyAdjustErr = true;
                        break;
                    }
                    if (type === "adjust" && $scope.orderObj.detailList[i].amount < $scope.orderObj.detailList[i].outAmount) {
                        listValid = false;
                        $scope.orderObj.detailList[i].qtyAdjustErr2 = true;
                        break;
                    }
                    // console.log($scope.orderObj.detailList[i].amount);
                    // console.log($scope.orderObj.detailList[i].oldAmount);
                    // console.log($scope.orderObj.detailList[i].outAmount);
                    // console.log(listValid);
                }
                }
                if (!listValid) {
                    return;
                }

                if (isErrorStockStatusForExcavatorCompany()) {
                  return;
                }

                var param = angular.copy($scope.orderObj);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                });
            };

            function isErrorStockStatusForExcavatorCompany() {
                // 暂时 农机使用这种配置
                if ($scope.isNJ) {
                  if (!UserContextService.NeedCheckStockQty('区域调拨单', $scope.curOrgId)) {
                    return false;
                  }
                } else {
                    if (!($scope.isWJ || $scope.isKJ)) {
                      return false;
                    }
                }

                for (var i = 0; i < $scope.orderObj.detailList.length; i++) {
                    if ($scope.orderObj.detailList[i].outState === undefined || $scope.orderObj.detailList[i].outState === 0) {
                        checkItemStockStatus($scope.orderObj.detailList[i], $scope.orderObj.detailList[i].amount);
                        if ($scope.orderObj.detailList[i].qtyStockErr && ($scope.orderObj.detailList[i].qtyStockErrLevel > 1)) {
                            ybWidget.ShowMessage("零件" + $scope.orderObj.detailList[i].materialsNo + "，" + $scope.orderObj.detailList[i].materialsDes + "库存不足，单据不能创建，请先删除该零件或取消提交", MESG_TYPE.Error);
                            $scope.clickValue = false;
                            return true;
                        }
                    }
                }
                return false;
            }

            $scope.cancel = function () {
                $scope.changeTab(0);
            };

            // 入库
            $scope.inbound = function (item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    // 入库时把入库的默认储位赋值给locationCode字段
                    angular.forEach(data.detailList, function (item) {
                        item.locationCode = item.inLocationCode;
                        item.estimatedShippingDateShow = $filter("YbDate")(item.estimatedShippingDate, 'yyyy-MM-dd HH:mm:ss');
                    });
                    $scope.detailInfo = data;
                    $scope.tabFlag.type = 4;
                    $scope.changeTab(6);
                });
            };

            $scope.inboundSubmit = function () {
                if (!$scope.detailInfo.headerInfo.inLocation) {
                    ybWidget.ShowMessage('请先选择仓库', MESG_TYPE.Error);
                    return;
                }

                var service = "device";
                var reqUrl = "/warehouseInboundRecord/receive";
                var param = {
                    headerInfo: {},
                    detailList: []
                };
                param.headerInfo.businessOrder = $scope.detailInfo.headerInfo.allotOrder;
                angular.forEach($scope.detailInfo.detailList, function (item) {
                    var listRow = {};
                    listRow.materialNo = item.materialNo;
                    listRow.locationCode = item.locationCode;
                    param.detailList.push(listRow);
                });

                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    getDataList();
                });
            };

            $scope.outboundSubmit = function () {
                if (!$scope.detailInfo.headerInfo.outLocation) {
                    ybWidget.ShowMessage('请先选择仓库', MESG_TYPE.Error);
                    return;
                }

                var service = "device";
                var reqUrl = "/warehouseDeliveryRecord/receive";
                var param = {
                    headerInfo: {},
                    detailList: []
                };
                param.headerInfo.businessOrder = $scope.detailInfo.headerInfo.allotOrder;
                angular.forEach($scope.detailInfo.detailList, function (item) {
                    var listRow = {};
                    listRow.materialNo = item.materialNo;
                    listRow.locationCode = item.locationCode;
                    param.detailList.push(listRow);
                });

                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    getDataList();
                });
            };

            $scope.selDepot = function (item) {
                var param = {};
                // 出库时取出库仓库的储位  入库时取入库仓库的储位
                if ($scope.tabFlag.type === 3) {
                    param.warehouseCode = $scope.detailInfo.headerInfo.outLocation;
                } else {
                    param.warehouseCode = $scope.detailInfo.headerInfo.inLocation;
                }
                ybWidget.DepotSelector(param).then(function (data) {
                    item.warehouseCode = data.warehouseCode;
                    item.areaCode = data.areaCode;
                    item.locationCode = data.locationCode;
                })
            };

            $scope.clearDepot = function (item) {
                item.warehouseCode = "";
                item.areaCode = "";
                item.locationCode = "";
            };

            // 出库
            $scope.outbound = function (item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    // wangcan:出库有多个库存储位时，默认展示第一个
                    angular.forEach(data.detailList, function (item) {
                        if (item.locationCode && item.locationCode.indexOf(',') != -1) {
                            var tempArr = item.locationCode.split(',');
                            item.locationCode = tempArr[0];
                        }
                        item.estimatedShippingDateShow = $filter("YbDate")(item.estimatedShippingDate, 'yyyy-MM-dd HH:mm:ss');
                    });
                    $scope.tabFlag.type = 3;
                    $scope.detailInfo = data;
                    $scope.changeTab(7);
                });
            };

            $scope.go2AllocationPlan = function () {
                $state.go("app.stock.allocationPlan", {
                    isCanKao: true
                })
            }

            /* 根据转入转出单号查询详情 */
            function getDetailByThreeOffset(id) {
                var param = {
                    allotOrder: id
                };
                return ybHttp.Get('device', '/regionAllot/itemByNo', param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    angular.forEach(resp.value.detailList, function (item) {
                        item.materialsDes = item.materialName;
                        item.materialsNo = item.materialNo;
                        checkItemStockStatus(item, item.amount);
                    });
                    return $scope.orderObj = resp.value;
                });
            }

            $scope.batchPosting = function() {
                const conditionList = $scope.dataList.filter(df => df.isChecked).map(dm => {
                    return {
                        businessOrder: dm.allotOrder,
                        inOut: 1,
                    }
                })

                if (conditionList.length === 0) {
                    ybWidget.ShowMessage('请选择需要操作的行');
                    return;
                }

                ybWidget.ShowMessage("确定要批量过账吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Post('device', '/warehouseInventory/obligatePostingBatch', conditionList).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                });
            };

            $scope.batchReserve = function() {
                const conditionList = $scope.dataList.filter(df => df.isChecked).map(dm => {
                    return {
                        businessOrder: dm.allotOrder,
                        id: dm.id,
                    }
                })

                if (conditionList.length === 0) {
                    ybWidget.ShowMessage('请选择需要操作的行');
                    return;
                }

                ybWidget.ShowMessage("确定要批量创建预留吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Post('device', '/warehouseInventory/createObligateOrderBatch', conditionList).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                });
            };

            function handleAttachFiles(attachNameStr) {
                if (!attachNameStr) {
                    return [];
                }
                return attachNameStr.split(',').map(an => {
                    const fName = an.split('/').pop()
                    return {
                        fileUrl: an,
                        name: fName,
                        filename: fName,
                        hasUpload: true,
                    }
                })
            }

            function viewAttach4sch(item) {
                ybWidget.FileUploader({fileList: handleAttachFiles(item.fileAttach), Type: 'view'})
            }

            $scope.importAttach4sch = function(item) {
                ybWidget.FileUploader({fileList: item.attachFiles4sch || handleAttachFiles(item.fileAttach), ignoreFormat: true}).then(res => {
                    const fileListTemp  = res.fileList || [];
                    item.attachFiles4sch = fileListTemp;
                    item.fileAttach = fileListTemp.filter(item => !!item.fileUrl).map(an => an.fileUrl).join(',');

                    const { id, fileAttach } = item;
                    ybHttp.Post('device', '/regionAllot/updateAttach', { id, fileAttach }).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        }
                    });
                })
            };

            (function () {
                getWarehouseType();
                var regionAllotOrder = window.sessionStorage.getItem("regionAllotOrder");
                window.sessionStorage.removeItem("regionAllotOrder");
                if (!!regionAllotOrder) {
                    $scope.condition.allotOrder = regionAllotOrder;
                    getDataList().then(function (data) {
                        viewDetail(data[0]);
                    })
                } else {
                    // $scope.condition.createName = $scope.isCHY ? $scope.curUser.name : undefined; // 后期可能会要
                    $scope.condition.deptName = $scope.isJCH ? $scope.curUser.deptName : undefined;
                    getDataList();
                }
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
                /* 三包冲销转区域调拨单 */
                if ($stateParams.canKaoObj) {
                    if ($stateParams.canKaoObj.regionAllotCodeType) {
                        /* 1、点击转入、转出单号 */
                        if ($stateParams.canKaoObj.regionAllotCodeType === '1') {
                            getDetailByThreeOffset($stateParams.canKaoObj.regionAllotCodeIn).then(function (data) {
                                if (!data) {
                                    return;
                                }
                                $scope.orderObj = data;
                                $scope.changeTab(1);
                            });
                        } else if ($stateParams.canKaoObj.regionAllotCodeType === '2') {
                            getDetailByThreeOffset($stateParams.canKaoObj.regionAllotCodeOut).then(function (data) {
                                if (!data) {
                                    return;
                                }
                                $scope.orderObj = data;
                                $scope.changeTab(1);
                            });
                        }
                    } else if ($stateParams.canKaoObj.createdStorage) { // 参考创建区域调拨计划
                        var detailListTemp = $stateParams.canKaoObj.detailVOList || [];
                        angular.forEach(detailListTemp, function (item) {
                            item.amount = item.planAmount - item.allotAmount;
                        })
                        $scope.orderObj.detailList = detailListTemp.filter(function (item) {
                            const filterFlagOld = item.amount > 0 && (item.planStatus !=3 && item.planStatus !=4) // 3 结单、4 已完成
                            if ($scope.isWJ) {
                                return filterFlagOld && item.enableNum > 0
                            }
                            return filterFlagOld
                        });
                        delete $stateParams.canKaoObj.detailVOList
                        $scope.orderObj.headerInfo = $stateParams.canKaoObj;
                        $scope.orderObj.headerInfo.outLocation = $stateParams.canKaoObj.outWarehouse;
                        $scope.orderObj.headerInfo.inLocation = $stateParams.canKaoObj.inWarehouse;
                        $scope.orderObj.headerInfo.allotPlanId = $stateParams.canKaoObj.id;
                        $scope.orderObj.headerInfo.allotType = 1;
                        $scope.orderObj.headerInfo.crmOrder = $stateParams.canKaoObj.crmOrder;
                        $scope.changeTab(2);
                    } else {
                        /* 2、点击转入、转出按钮 */
                        var detailListTemp = $stateParams.canKaoObj.detailVOList || [];
                        $scope.orderObj.detailList = detailListTemp;
                        delete $stateParams.canKaoObj.detailVOList
                        $scope.orderObj.headerInfo.threeReverseType = $stateParams.canKaoObj.threeReverseType;
                        $scope.orderObj.headerInfo.threeReverseId = $stateParams.canKaoObj.threeReverseId;
                        /* 三包冲销带过来的字段 */
                        if ($stateParams.canKaoObj.threeReverseType === '1') { // 转出
                            $scope.orderObj.headerInfo.outLocation = $stateParams.canKaoObj.warehouseCode;
                            $scope.orderObj.headerInfo.outArea = $stateParams.canKaoObj.inArea;
                        } else if ($stateParams.canKaoObj.threeReverseType === '2') { // 转入
                            $scope.orderObj.headerInfo.inLocation = $stateParams.canKaoObj.warehouseCode;
                            $scope.orderObj.headerInfo.inArea = $stateParams.canKaoObj.inArea;
                        }
                        $scope.orderObj.headerInfo.createDate = +new Date();
                        setUserInfo();
                        $scope.changeTab(2);
                    }
                }
            })();
        }]);
})(window, window.angular);
